package cc.linker.steplink.crm.merchant.controller.acs;

import cc.linker.steplink.crm.commons.constant.TlPayConstant;
import cc.linker.steplink.crm.commons.constant.WcPayConstant;
import cc.linker.steplink.crm.commons.http.HttpService;
import cc.linker.steplink.crm.commons.model.PcUserInfo;
import cc.linker.steplink.crm.commons.model.WcPayProperties;
import cc.linker.steplink.crm.commons.utils.CommUtils;
import cc.linker.steplink.crm.commons.utils.StringUtil;
import cc.linker.steplink.crm.merchant.service.MallService;
import cc.linker.steplink.crm.merchanth5.commons.UserInfoUtil;
import cc.linker.steplink.crm.merchant.service.acs.PlatformSetNameService;
import cc.linker.steplink.crm.merchanth5.service.MaiBaoLaService;
import cc.linker.steplink.crm.merchanth5.service.redis.SystemConfigService;
import cc.linker.steplink.crm.response.GlobalException;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import com.alibaba.fastjson.JSON;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 平台设置自定义名称
 */
@Slf4j
@RequestMapping("/platform")
@RestController
public class PlatformSetNameController {
    @Autowired
    private PlatformSetNameService platformSetNameService;
    @Autowired
    private MaiBaoLaService maiBaoLaService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private UserInfoUtil userInfoUtil;
    @Autowired
    private WcPayProperties wcPayProperties;
    @Autowired
    private HttpService httpService;
    @Autowired
    private MallService mallService;

    @RequestMapping("/looksetting")
    public Map<String, Object> lookSetting(HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        return platformSetNameService.lookSetting(userinfo.getOrgId());
    }

    @RequestMapping("/setting")
    public void setName(@RequestBody Map param,HttpServletRequest request) throws GlobalException {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        Map<String, Object> map = new HashMap<>();
        if (null != param) {
            if (null != param.get("promoterName") && !"".equals(param.get("promoterName"))) {
                if (param.get("promoterName").toString().length() <= 6) {
                    map.put("promoterName", param.get("promoterName"));
                } else {
                    throw GlobalException.build("请输入不大于6个字数的名称");
                }
            } else {
                throw GlobalException.build("请先填写完整信息");
            }
            if (null != param.get("mallName") && !"".equals(param.get("mallName"))) {
                if (param.get("mallName").toString().length() <= 6) {
                    map.put("mallName", param.get("mallName"));
                } else {
                    throw GlobalException.build("请输入不大于6个字数的名称");
                }
            } else {
                throw GlobalException.build("请先填写完整信息");
            }
            if (null != param.get("salerName") && !"".equals(param.get("salerName"))) {
                if (param.get("salerName").toString().length() <= 6) {
                    map.put("salerName", param.get("salerName"));
                } else {
                    throw GlobalException.build("请输入不大于6个字数的名称");
                }
            } else {
                throw GlobalException.build("请先填写完整信息");
            }
            if (null != param.get("agentName") && !"".equals(param.get("agentName"))) {
                if (param.get("agentName").toString().length() <= 6) {
                    map.put("agentName", param.get("agentName"));
                } else {
                    throw GlobalException.build("请输入不大于6个字数的名称");
                }
            } else {
                throw GlobalException.build("请先填写完整信息");
            }
        }
        map.put("orgId", orgId);
        Map<String, Object> stringObjectMap = platformSetNameService.lookSetting(userinfo.getOrgId());
        if (null != stringObjectMap) {
            platformSetNameService.updateNameSet(map);
        } else {
            platformSetNameService.setName(map);
        }

    }

    @GetMapping("/getpaysetting")
    public Map<String, Object> getPaySetting(String orgId) {
        return platformSetNameService.getPaySetting(orgId);
    }

    @PostMapping("/paySetting")
    public void paySetting(@RequestBody Map<String, Object> param) throws Exception {
        boolean paramState = true;
        if (null != param) {
            if (null == param.get("zjPayId") || "".equals(param.get("zjPayId"))) {
                paramState = false;
            }
            if ((null == param.get("withdrawRate") || "".equals(param.get("withdrawRate")))
                    && (null == param.get("withdrawCost") || "".equals(param.get("withdrawCost")))) {
                paramState = false;
            }
            if (null == param.get("withdrawLimit") || "".equals(param.get("withdrawLimit"))) {
                paramState = false;
            }
            if (null == param.get("linkerRate") || "".equals(param.get("linkerRate"))) {
                paramState = false;
            }
            if (null == param.get("unionBarleyTake") || "".equals(param.get("unionBarleyTake"))) {
                paramState = false;
            }
            if (null == param.get("orgId") || "".equals(param.get("orgId"))) {
                paramState = false;
            }
            if (null == param.get("withdrawTakeType") || "".equals(param.get("withdrawTakeType"))) {
                paramState = false;
            }
            if (paramState && (null == param.get("payMode") || "".equals(param.get("payMode")))) {
                throw GlobalException.build("请先填写完整信息");
            }
        }
        if (StringUtils.isEmpty(param.get("withdrawCost"))) {
            param.put("withdrawCost", 0);
        }
        Double withdrawCost = Double.parseDouble(param.get("withdrawCost").toString()) * 100;
        Double withdrawLimit = Double.parseDouble(param.get("withdrawLimit").toString()) * 100;
        param.put("withdrawCost", withdrawCost.intValue());
        param.put("withdrawLimit", withdrawLimit.intValue());
        // 判断提现抽成 固定金额的情况 判断最小提现金额大于抽成
        if ("2".equals(param.get("withdrawTakeType"))) {
            if (withdrawLimit.intValue() <= withdrawCost.intValue()) {
                throw GlobalException.build("最小提现金额必须大于提现抽成！");
            }
        }
        if (platformSetNameService.ifExist(param)) {
            platformSetNameService.updatePaySetting(param);
        } else {
            platformSetNameService.savePaySetting(param);
        }
        // 删除缓存 生成缓存
        String orgId = param.get("orgId").toString();
        stringRedisTemplate.delete(SystemConfigService.ORG_PAY_KEY + orgId);
        stringRedisTemplate.opsForValue().set(SystemConfigService.ORG_PAY_KEY + orgId, JSON.toJSONString(param, SerializerFeature.WriteMapNullValue));
    }

    @PostMapping("/capitalAccountApply")
    public Object capitalAccountApply(@RequestBody Map<String, Object> param,HttpServletRequest request) throws Exception {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        if (!StringUtils.isEmpty(param.get("orgId"))) {
            orgId = (String) param.get("orgId");
        }
        String adminId = userinfo.getAdminId();
        String infoId = platformSetNameService.getInfoIdByAdminId(adminId);
        param.put("infoId",infoId);

        String customerId = "LINKER" + StringUtil.getRandomString(10);
        param.put("customerId", customerId);
        param.put("accoutType", "2");
        param.put("clintType", maiBaoLaService.getAlias(orgId));
        param.put("customerType", "12");
        param.put("scale", "8");
        param.put("source", "2");
        // 上传资料到通联ftp
//        Boolean temp = platformSetNameService.uploadFiles(param,orgId);
        if(!StringUtils.isEmpty(infoId)){
            Boolean temp = platformSetNameService.uploadFilesNew(param,orgId);
            if(!temp){
                throw GlobalException.build("资料上传通联ftp失败");
            }
        }
        return platformSetNameService.capitalAccountApply(CommUtils.mapRemoveNull(param));
    }

    /**
     * @Description: 获取联汇资金账户信息
     * @Return: 状态 0=未开通 20=审核中，30=成功，40=失败
     * @Author: 锋
     * @Date: 2019/10/14 17:30
     * @Version: 1.9.1
     */
    @GetMapping("/capitalAccountInfo")
    public Object capitalAccountInfo() {
        return platformSetNameService.capitalAccountInfo();
    }


    /**
     * 获取已关联的 模板
     *
     * @param session
     * @return 亮
     */
    @GetMapping("/getimage")
    public Map getImage(HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        Map result = platformSetNameService.getImage(orgId);
        if (result == null || StringUtils.isEmpty(result.get("salerImg")) || StringUtils.isEmpty(result.get("agentImg"))) {
            String salerImg = platformSetNameService.getModeImage(1);
            String agentImg = platformSetNameService.getModeImage(2);
            if(result!=null){
                if(!StringUtils.isEmpty(result.get("salerImg"))){
                    salerImg = result.get("salerImg").toString();
                }
                if(!StringUtils.isEmpty(result.get("agentImg"))){
                    agentImg = result.get("agentImg").toString();
                }
            }
            Map<String, Object> temp = new HashMap<>();
            temp.put("salerImg", salerImg);
            temp.put("agentImg", agentImg);
            return temp;
        }
        return result;
    }


    /**
     * 设置模板
     *
     * @param param
     * @param session 亮
     */
    @PostMapping("/setimage")
    public void setImage(
            @RequestBody Map<String, Object> param,
            HttpServletRequest request
    ) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        param.put("orgId", userinfo.getOrgId());
        platformSetNameService.setImage(param);
    }

    /**
     * 获取 模板
     *
     * @param session
     * @return 亮
     */
    @GetMapping("/getmould")
    public PageInfo getMould(
            @RequestParam(value = "pageIndex", defaultValue = "1", required = false) int pageIndex,
            @RequestParam(value = "pageSize", defaultValue = "10", required = false) int pageSize,
            @RequestParam(value = "type", defaultValue = "1", required = true) String type,
            HttpServletRequest request
    ) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        PageHelper.startPage(pageIndex, pageSize);
        return new PageInfo<>(platformSetNameService.getMould(userinfo.getOrgId(), type));
    }

    /**
     * 删除模板
     *
     * @param param
     * @param session 亮
     */
    @PostMapping("/delmould")
    public void delMould(
            @RequestBody Map<String, Object> param,
            HttpServletRequest request
    ) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        param.put("orgId", userinfo.getOrgId());
        platformSetNameService.delMould(param);
    }


    /**
     * 添加模板
     *
     * @param param
     * @param session 亮
     */
    @PostMapping("/addmould")
    public void addMould(
            @RequestBody Map<String, Object> param,
            HttpServletRequest request
    ) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        param.put("orgId", userinfo.getOrgId());
        platformSetNameService.addMould(param);

    }

    /**
     * 给管理中心的平台下拉列表
     *
     * @return
     */
    @GetMapping("/platformlist")
    public List<Map<String, Object>> platformList() {
        return platformSetNameService.platformList();
    }

    /**
     * 给管理中心的商户号平台下拉列表
     *
     * @return
     */
    @GetMapping("/bussinessaccountlist")
    public List<Map<String, Object>> bussinessAccountList(
            String platformId) {
        return platformSetNameService.bussinessAccountList(platformId);
    }
}
